<?php
/**
 *
 * PHP API 订单控制器
 * @author jeff liu
 * powered by jeff liu 2011-08-25
 */
class OrderApp extends ApiApp
{

    function __construct()
    {
        $this->OrderApp();
    }

    function OrderApp()
    {
        parent::__construct();
    }

    /**
     * 获得商品的销售记录
     * @id string required 商品id 多个
     * powered by jeff 2011-8-24
     */
    function apiGetGoodsSaleRank()
    {
        $begin_time = '';
        $end_time = '';
        if (isset($_REQUEST['begin_time'])) {
            $begin_time = $_REQUEST['begin_time'];
        }
        if (isset($_REQUEST['end_time'])) {
            $end_time = $_REQUEST['end_time'];
        }
        $group_by = $_REQUEST['group_by'];
        if (empty($begin_time) || empty($end_time)) {
            ApiError::showError('time_range_required', 1);
            return;
        }
        if (empty($group_by)) {
            ApiError::showError('group_by_required', 1);
            return;
        }
        $order_goods_mod =& api_model('ordergoods');
        $query_goods_id = 'SELECT og.goods_id FROM ' . $order_goods_mod->setTable('order') . ' o
                           LEFT JOIN ' . $order_goods_mod->setTable('order_goods') . ' og
                           ON og.order_id=o.order_id
                           WHERE o.add_time >=' . (float)$begin_time .
            ' AND o.add_time <=' . (float)$end_time;
        $tmp_goods_id = $order_goods_mod->getAll($query_goods_id);
        $sales_list = '';
        if (!empty($tmp_goods_id)) {
            $goods_ids = array();
            foreach ($tmp_goods_id as $goods) {
                if (!empty($goods['goods_id'])) {
                    $goods_ids[] = $goods['goods_id'];
                }
            }
            if (!empty($goods_ids)) {
                $query_final_info = 'SELECT g.goods_id, g.goods_name, g.store_id, sum(og.quantity) as sale_num FROM ' .
                    $order_goods_mod->table . ' og LEFT JOIN ' .
                    $order_goods_mod->setTable('goods') . ' g ' .
                    'ON og.goods_id=g.goods_id ' .
                    ' WHERE g.goods_id IN(' . implode(',', $goods_ids) . ') AND g.type = "car"
                                      GROUP BY g.' . $group_by . ' ORDER BY sale_num DESC ';
                $count_sql = 'SELECT count(*) as total FROM (' . $query_final_info . ') www';
                $total = $order_goods_mod->getOne($count_sql);
                if (!empty($_REQUEST['limit']) && is_numeric($_REQUEST['limit'])) {
                    $page = (int)$_REQUEST['page'];
                    if ($page > 0) {
                        $page = $page - 1;
                    }
                    $limit = $_REQUEST['limit'];
                    $start = $page * $limit;
                    $query_final_info .= ' LIMIT ' . $start . ',' . $limit;
                }
                $items = $order_goods_mod->getAll($query_final_info);
                $sales_list['total'] = $total;
                $sales_list['items'] = $items;
            } else {
                $sales_list = array();
            }

        } else {
            $sales_list = array();
        }

        $this->echo_result($sales_list);
    }

    /**
     * 通话商品销售总额获得店铺销售排行并排序
     * @author yanshuai
     */
    function apiGetStoreSellSortBySeledPrice()
    {
        $rs = $this->_getStoreSellSortBySaledPrice();
        //$this->echo_result($rs);
        echo $rs;
        exit();
    }

    /**
     * @author yanshuai
     * 通话商品销售总额获得店铺销售排行并排序
     * 支持时间段内的比较
     */
    private function _getStoreSellSortBySaledPrice()
    {
        $_order_mod = & m('order');
        $_store_mod = & m('store');
        $conditions = sprintf('%s.status >="%s" ', $_order_mod->alias, ORDER_ACCEPTED); //销售记录为所有已付款状态之后的订单（包括已付款）
        if (isset($_REQUEST['begin_time'])) {
            $begin_time = $_REQUEST['begin_time'];
        }
        if (isset($_REQUEST['end_time'])) {
            $end_time = $_REQUEST['end_time'];
        }
        //若有时间限制，则需要进行判断限制
        if (!empty($begin_time) && !empty($end_time)) {
            $conditions .= sprintf(
                ' and %s.add_time >= %s and %s.add_time <= %s ',
                $_order_mod->alias,
                $begin_time,
                $_order_mod->alias,
                $end_time
            );
        }
        $store_id = implode(',', $this->_get_goods_ids());
        if (empty($store_id)) {
            return null;
        }
        $conditions .= sprintf('and %s.seller_id in (%s)', $_order_mod->alias, $store_id);
        $rs = $_order_mod->find(
            array(
                'conditions' => $conditions . ' group by seller_id',
                'join' => 'belongs_to_store',
                'fields' => 'store_name,sum(order_amount) as total_amount,store_id',
                'order' => 'total_amount desc',
                'index_key' => 'store_id',
            )
        );
        return $this->return_result($rs);
    }

    /**
     * 获得补贴系统需要的数据
     * @author yanshuai
     */
    public function apiGetOrderInfoByOrderSn()
    {
        $order_sn = trim($_REQUEST['order_sn']);
        $_order_mod = & m('order');
        $_store_mod = & m('store');
        $rs = $_order_mod->find(
            array(
                'conditions' => '1=1 AND order_sn = "' . $order_sn . '"',
                'join' => 'belongs_to_store',
                'fields' => 'store_name,store_id,order_sn,status',
                'index_key' => 'order_sn'
            )
        );
        if (!empty($rs) && count($rs) == 1) {
            $this->echo_result($rs[$order_sn]);
            exit;
        } else {
            $this->echo_result(array());
            exit;
        }
    }
}